package com.atguigu.ossservice.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.ossservice.utils.ConstantPropertiesUtil;
import com.atguigu.servicebase.handler.GuliException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Auther 赵乾坤
 * @Date 2020-11-23 9:32
 */
@Service
public class FileServiceImpl  implements FileService {
    @Override
    public String uploadFileOSS(MultipartFile file) {
// Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtil.END_POINT;
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileName = file.getOriginalFilename();

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
// 上传文件流。
            //优化文件名(11111222 +01.jpg)
            fileName = UUID.randomUUID().toString() + fileName;
            //优化文件存储路径(/2020/11/23/01.jpg)
            String path = new DateTime().toString("yyyy/MM/dd");
            fileName = path+"/"+fileName;

            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, fileName, inputStream);

// 关闭OSSClient。
            ossClient.shutdown();
            //https://guli-file19980720.oss-cn-shenzhen.aliyuncs.com/20201022.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"上传失败");
        }
    }
}
